package com.bwt.tree;

public class ArrBinaryTreeDemo {
	public static void main(String[] args) {
		int[] arr = {1, 2, 3, 4, 5, 6, 7};
		ArrBinaryTree arrBinaryTree = new ArrBinaryTree(arr);
		arrBinaryTree.preOreder(0); // 1245367
		arrBinaryTree.infixOrder(0); // 4251637
	}
}

//编写一个ArrBinaryTree,实现顺序存储二叉树
class ArrBinaryTree{
	private int[] arr; //存储数据节点的数组

	public ArrBinaryTree(int[] arr) {
		this.arr = arr;
	}

	// 顺序存储二叉树的前序遍历
	/**
	 *
	 * @param index 数组的下标
	 */
	public void preOreder(int index) {
		//如果数组为空
		if (arr == null || arr.length == 0) {
			System.out.println("数组为空,不能按照二叉数的前序遍历");
		}
		//输出当前这个元素
		System.out.println(arr[index]);
		int leftIndex = 2 * index + 1;
		if (arr.length > leftIndex) {
			preOreder(leftIndex);
		}
		int rightIndex = (2 * index) + 2;
		if (rightIndex < arr.length) {
			preOreder(rightIndex);
		}
	}

	// 中序遍历
	public void infixOrder(int index) {
		//如果数组为空,或arr.length = 0
		if(arr == null || arr.length == 0){
			System.out.println("数组为空,无法遍历查找。");
		}
		if (index * 2 + 1 < arr.length) {
			infixOrder(index * 2 + 1);
		}
		System.out.println(arr[index]);
		if (index * 2 + 2 < arr.length) {
			infixOrder(index * 2 + 2);
		}
	}

	public void postOrder(int index) {
		//如果数组为空,或arr.length = 0
		if(arr == null || arr.length == 0){
			System.out.println("数组为空,无法遍历查找。");
		}
		if (index * 2 + 1 < arr.length) {
			postOrder(index * 2 + 1);
		}
		if (index * 2 + 2 < arr.length) {
			postOrder(index * 2 + 2);
		}
		System.out.println(arr[index]);
	}
}

